package com.strongbj.iot.devices.dam.response.handle.v1;

import java.util.ArrayList;
import java.util.List;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import com.alibaba.fastjson.JSON;
import com.strongbj.core.util.ByteUtil;
import com.strongbj.core.util.ContextUtils;
import com.strongbj.iot.devices.dam.message.DAMMessage;
import com.strongbj.iot.devices.dam.message.MQMessageOfDAM;
import com.strongbj.iot.devices.dam.response.entity.SensorEntity;
import com.strongbj.iot.devices.dam.response.entity.TemperatureAndHumiditySensorFactory;
import com.strongbj.iot.devices.dam.response.entity.TemperatureSensorFactory;
import com.strongbj.iot.mq.producer.TopicSender;

import io.netty.channel.ChannelHandlerContext;

public class TemperatureAndHumidityHandleV0_3 extends DAMV1Handle {
	private static Logger logger = LogManager.getLogger(TemperatureAndHumidityHandle.class.getName());
	private TopicSender topicSender = (TopicSender) ContextUtils.getBean("topicSender");
	private static final String ACTION_CODE = "DAMCollect032";
	
//	private final static int SENSOR_DATA_SIZE=3;	// 一个传感器在协议里的字节长度
	private final static int TEMPERATURE_SENSOR_COUNT=6;	// 温度传感器的数量
	private TemperatureSensorFactory temperatureSensorFactory=new TemperatureSensorFactory();	// 传感器工厂类
	private TemperatureAndHumiditySensorFactory temperatureAndHumiditySensorFactory = new TemperatureAndHumiditySensorFactory();
	@Override
	protected boolean isHandleDAMMessage(DAMMessage t) {
		if(t.getCommand()==0x32){
			return true;
		}else{
			return false;
		}
	}

	@Override
	public Object handle(ChannelHandlerContext ctx, DAMMessage t) {
		List<SensorEntity> sensorList = new ArrayList<>();
		for(int i=0;i<TEMPERATURE_SENSOR_COUNT;i++){
			SensorEntity sensor = temperatureSensorFactory.createSensor(t.getDatas(), i*3);
			sensorList.add(sensor);
		}
		
		SensorEntity sensor = temperatureAndHumiditySensorFactory.createSensor(t.getDatas(), t.getDatas().length-5);
		sensorList.add(sensor);
		
		MQMessageOfDAM msg = new MQMessageOfDAM();
		msg.setActioncode(ACTION_CODE);
		msg.setAwsPostdata(sensorList);
		msg.setTimestamp(ByteUtil.bytesToLong(t.getSn()));
		String json = JSON.toJSONString(msg);
		logger.debug("DAM设备 向MQ发送温湿度数据	 JSON={}",json);
		topicSender.send("DAM", json);
		
		sensorList.clear();
		sensorList=null;
		return null;
	}
}

